package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/admin/common")
@RestController
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Resource(name = "aliOssUtil")
    AliOssUtil aliOssUtil;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result<String> upLoad(MultipartFile file) {
        //构建文件名（唯一标识）
        String originalFilename = file.getOriginalFilename();//获取原始文件名
        String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));//获取文件.后缀名
        String fileName = UUID.randomUUID() + fileType;//拼接文件名
        //调用阿里云上传文件
        try {
            String url = aliOssUtil.upload(file.getBytes(), fileName);
            log.info("上传成功，返回路径为：{}", url);
            return Result.success(url);
        } catch (IOException e) {
            log.info("上传失败，异常：{}", e);
        }
        return Result.error("上传失败,请联系管理员。");
    }
}
